// 现代化聊天应用前端JavaScript

let socket = null;
let currentSessionId = null;
let isTyping = false;

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    setupEventListeners();
    loadSettings();
});

// 初始化应用
function initializeApp() {
    // 初始化Socket.io连接
    socket = io();
    
    // Socket事件监听
    socket.on('connect', () => {
        console.log('Connected to server');
        currentSessionId = socket.id;
    });
    
    socket.on('message', (data) => {
        addMessage(data.message, 'assistant', data.is_complete);
        if (data.is_complete) {
            enableInput();
        }
    });
    
    socket.on('typing', (data) => {
        showTypingIndicator(data.is_typing);
    });
    
    socket.on('error', (error) => {
        console.error('Socket error:', error);
        addMessage('抱歉，发生了错误：' + error.message, 'error');
        enableInput();
    });
    
    socket.on('disconnect', () => {
        console.log('Disconnected from server');
    });
    
    // 自动调整输入框高度
    autoResizeTextarea();
}

// 设置事件监听器
function setupEventListeners() {
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    const themeToggle = document.getElementById('themeToggle');
    
    // 输入框事件
    messageInput.addEventListener('input', autoResizeTextarea);
    messageInput.addEventListener('keydown', handleInputKeydown);
    
    // 发送按钮事件
    sendButton.addEventListener('click', sendMessage);
    
    // 主题切换
    themeToggle.addEventListener('click', toggleTheme);
    
    // 模型和角色选择变化
    document.getElementById('modelSelect').addEventListener('change', updateSettings);
    document.getElementById('roleSelect').addEventListener('change', updateSettings);
    document.getElementById('thinkingToggle').addEventListener('change', updateSettings);
    
    // 窗口调整时重新计算高度
    window.addEventListener('resize', autoResizeTextarea);
}

// 自动调整文本区域高度
function autoResizeTextarea() {
    const textarea = document.getElementById('messageInput');
    textarea.style.height = 'auto';
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
}

// 处理键盘输入
function handleInputKeydown(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
}

// 发送消息
function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message || isTyping) return;
    
    // 获取当前设置
    const model = document.getElementById('modelSelect').value;
    const role = document.getElementById('roleSelect').value;
    const deepThinking = document.getElementById('thinkingToggle').checked;
    
    // 添加用户消息到聊天区域
    addMessage(message, 'user');
    
    // 清空输入框并禁用输入
    messageInput.value = '';
    messageInput.style.height = 'auto';
    disableInput();
    
    // 发送消息到服务器
    socket.emit('send_message', {
        message: message,
        model: model,
        role: role,
        deep_thinking: deepThinking,
        session_id: currentSessionId
    });
}

// 添加消息到聊天区域
function addMessage(content, type, isComplete = true) {
    const chatMessages = document.getElementById('chatMessages');
    
    // 移除欢迎消息（如果是第一条用户消息）
    if (type === 'user' && chatMessages.querySelector('.text-center')) {
        chatMessages.innerHTML = '';
    }
    
    // 移除正在输入指示器
    const typingIndicator = chatMessages.querySelector('.typing-indicator');
    if (typingIndicator) {
        typingIndicator.remove();
    }
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message flex ${type === 'user' ? 'justify-end' : 'justify-start'}`;
    
    const messageContent = document.createElement('div');
    messageContent.className = `max-w-xs lg:max-w-md px-4 py-3 rounded-2xl ${
        type === 'user' 
            ? 'message-user' 
            : type === 'error' 
                ? 'bg-red-100 text-red-800 border border-red-200'
                : 'message-assistant'
    }`;
    
    if (type === 'assistant' && !isComplete) {
        // 显示Markdown格式的消息（如果是AI回复）
        messageContent.innerHTML = renderMarkdown(content);
    } else {
        messageContent.textContent = content;
    }
    
    messageDiv.appendChild(messageContent);
    chatMessages.appendChild(messageDiv);
    
    // 滚动到底部
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 显示正在输入指示器
function showTypingIndicator(show) {
    const chatMessages = document.getElementById('chatMessages');
    const existingIndicator = chatMessages.querySelector('.typing-indicator');
    
    if (show && !existingIndicator) {
        const indicatorDiv = document.createElement('div');
        indicatorDiv.className = 'typing-indicator flex justify-start';
        
        const indicatorContent = document.createElement('div');
        indicatorContent.className = 'px-4 py-3 rounded-2xl message-assistant';
        indicatorContent.innerHTML = `
            <div class="flex items-center gap-2">
                <span class="text-gray-500">AI正在思考</span>
                <div class="flex gap-1">
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                </div>
            </div>
        `;
        
        indicatorDiv.appendChild(indicatorContent);
        chatMessages.appendChild(indicatorDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    } else if (!show && existingIndicator) {
        existingIndicator.remove();
    }
    
    isTyping = show;
}

// 禁用输入
function disableInput() {
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    
    messageInput.disabled = true;
    sendButton.disabled = true;
    isTyping = true;
}

// 启用输入
function enableInput() {
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    
    messageInput.disabled = false;
    sendButton.disabled = false;
    messageInput.focus();
    isTyping = false;
}

// 清空聊天
function clearChat() {
    if (confirm('确定要清空当前聊天记录吗？')) {
        const chatMessages = document.getElementById('chatMessages');
        chatMessages.innerHTML = `
            <div class="text-center py-8">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-blue-100 rounded-full mb-4">
                    <i class="fas fa-robot text-2xl text-blue-600"></i>
                </div>
                <h2 class="text-xl font-semibold text-gray-700 mb-2">欢迎使用AI聊天助手</h2>
                <p class="text-gray-500 text-sm">开始与AI助手对话吧！选择不同的模型和角色可以获得不同的体验。</p>
            </div>
        `;
        
        // 通知服务器清空会话
        socket.emit('clear_chat', { session_id: currentSessionId });
    }
}

// 添加快捷提示
function addQuickPrompt(prompt) {
    const messageInput = document.getElementById('messageInput');
    messageInput.value = prompt;
    messageInput.focus();
    autoResizeTextarea();
}

// 切换主题
function toggleTheme() {
    const body = document.body;
    const themeIcon = document.querySelector('#themeToggle i');
    
    if (body.classList.contains('dark-mode')) {
        body.classList.remove('dark-mode');
        themeIcon.className = 'fas fa-moon text-gray-600';
        localStorage.setItem('theme', 'light');
    } else {
        body.classList.add('dark-mode');
        themeIcon.className = 'fas fa-sun text-yellow-500';
        localStorage.setItem('theme', 'dark');
    }
}

// 打开设置
function openSettings() {
    document.getElementById('settingsModal').classList.remove('hidden');
}

// 关闭设置
function closeSettings() {
    document.getElementById('settingsModal').classList.add('hidden');
}

// 保存设置
function saveSettings() {
    const typingSpeed = document.getElementById('typingSpeed').value;
    
    const settings = {
        typingSpeed: parseInt(typingSpeed),
        apiKeys: {}
    };
    
    // 保存API密钥
    document.querySelectorAll('input[id^="apiKey_"]').forEach(input => {
        const model = input.id.replace('apiKey_', '');
        if (input.value) {
            settings.apiKeys[model] = input.value;
        }
    });
    
    localStorage.setItem('chatSettings', JSON.stringify(settings));
    closeSettings();
    
    // 显示保存成功提示
    showToast('设置已保存');
}

// 加载设置
function loadSettings() {
    // 加载主题
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark') {
        document.body.classList.add('dark-mode');
        document.querySelector('#themeToggle i').className = 'fas fa-sun text-yellow-500';
    }
    
    // 加载聊天设置
    const savedSettings = localStorage.getItem('chatSettings');
    if (savedSettings) {
        const settings = JSON.parse(savedSettings);
        
        if (settings.typingSpeed) {
            document.getElementById('typingSpeed').value = settings.typingSpeed;
            document.getElementById('speedValue').textContent = settings.typingSpeed + 'ms';
        }
        
        if (settings.apiKeys) {
            Object.entries(settings.apiKeys).forEach(([model, key]) => {
                const input = document.getElementById(`apiKey_${model}`);
                if (input) {
                    input.value = key;
                }
            });
        }
    }
}

// 更新设置（实时保存）
function updateSettings() {
    const settings = {
        model: document.getElementById('modelSelect').value,
        role: document.getElementById('roleSelect').value,
        deepThinking: document.getElementById('thinkingToggle').checked
    };
    
    localStorage.setItem('currentSettings', JSON.stringify(settings));
}

// 显示Toast提示
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `fixed top-4 right-4 px-4 py-2 rounded-lg shadow-lg z-50 ${
        type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
    }`;
    toast.textContent = message;
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// 简单的Markdown渲染
function renderMarkdown(text) {
    // 代码块
    text = text.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>');
    
    // 内联代码
    text = text.replace(/`([^`]+)`/g, '<code>$1</code>');
    
    // 粗体
    text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    text = text.replace(/__(.*?)__/g, '<strong>$1</strong>');
    
    // 斜体
    text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
    text = text.replace(/_(.*?)_/g, '<em>$1</em>');
    
    // 链接
    text = text.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank" class="text-blue-600 hover:underline">$1</a>');
    
    // 列表
    text = text.replace(/^\s*[-*]\s+(.+)$/gm, '<li>$1</li>');
    text = text.replace(/(<li>.*<\/li>)+/gs, '<ul>$&</ul>');
    
    // 引用
    text = text.replace(/^>\s+(.+)$/gm, '<blockquote>$1</blockquote>');
    
    return text;
}

// 全局键盘快捷键
document.addEventListener('keydown', function(event) {
    // Ctrl/Cmd + K 聚焦输入框
    if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
        event.preventDefault();
        document.getElementById('messageInput').focus();
    }
    
    // Esc 关闭模态框
    if (event.key === 'Escape') {
        closeSettings();
    }
    
    // Ctrl/Cmd + / 打开设置
    if ((event.ctrlKey || event.metaKey) && event.key === '/') {
        event.preventDefault();
        openSettings();
    }
});